package fr.xelaprod.open.source.android.rss.object;

import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadRSS extends BaseFeedParser {

	public ReadRSS(String feedUrl) {
		super(feedUrl);

	}

	public List<Item> parse(int limitBegin,int limitEnd) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		List<Item> listOfItems = new ArrayList<Item>();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document dom = builder.parse(this.getInputStream());
			Element root = dom.getDocumentElement();
			NodeList items = root.getElementsByTagName(ITEM);
			
			Node item ;
			NodeList properties;
			Node property;
			NodeList chars ;
			for (int i = 0; i < limitEnd; i++) {
				if(i>=limitBegin)
				{
					Item itemm = new Item();
					item = items.item(i);
					properties = item.getChildNodes();
					for (int j = 0; j < properties.getLength(); j++) {
						property = properties.item(j);
						String name = property.getNodeName();
						if (name.equalsIgnoreCase(TITLE)) {
							itemm.setTitle(property.getFirstChild().getNodeValue());
						} else if (name.equalsIgnoreCase(LINK)) {
							itemm.setLink(property.getFirstChild().getNodeValue());
						} else if (name.equalsIgnoreCase(DESCRIPTION)) {
							StringBuilder text = new StringBuilder();
							chars = property.getChildNodes();
							for (int k = 0; k < chars.getLength(); k++) {
								text.append(chars.item(k).getNodeValue());
							}
							itemm.setDescription(text.toString());
						} else if (name.equalsIgnoreCase(PUB_DATE)) {
							itemm.setPubDate(property
									.getFirstChild().getNodeValue());
						}
					}
					listOfItems.add(itemm);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return listOfItems;
	}
}
